package com.frxuexi.mine

import android.os.Bundle
import android.text.TextUtils
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.mine.databinding.FragmentMineBinding
import com.frxuexi.mine.entity.User
import com.frxuexi.mine.room.AppDataBase
import com.frxuexi.mine.room.UserViewModelFactory
import kotlinx.coroutines.launch


@Route(path = "/mine/MineFragment")
class MineFragment : Fragment() {
    val vm by lazy {
        UserViewModelFactory(UserRepository.getInstance(AppDataBase.getInstance(requireContext())))
            .create(UserViewModel::class.java)
    }

    lateinit var db:FragmentMineBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        db= FragmentMineBinding.inflate(layoutInflater, container, false)

        lifecycleScope.launch {
            vm.userState.collect{
                when(it){
                    is UserState.onRegisterSuccess->{
                        ToastUtils.showLong("注册成功")
                    }
                    else->{}
                }
            }
        }

        db.mineCom.setContent {
                myLogin(){name,pass->
                    if(TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)){
                        ToastUtils.showLong("账号和密码都不能为空")
                        return@myLogin
                    }

                    /*if(!name.matches(Regex("1[0-9]{10}"))){
                        ToastUtils.showLong("不是合法手机号")
                        return
                    }*/

                    /*if(!name.matches(Regex("[0-9A-z_]{6,12}@[0-9a-z]{2,5}.com"))){
                        ToastUtils.showLong("不是合法邮箱")
                        return
                    }*/
                    if(!RegexUtils.isUsername(name)){
                        ToastUtils.showLong("不是合法用户名")
                        return@myLogin
                    }

                    lifecycleScope.launch {
                        vm.channel.send(UserIntent.register(User(uname = name, upass = pass)))
                        vm.channel.send(UserIntent.login(name, pass))
                    }
                }
        }

        return db.root
    }

}